import javax.crypto.*;
import java.security.*;
import java.security.spec.*;
import java.io.*;
import java.security.*;
import java.security.GeneralSecurityException;
import java.math.BigInteger;

/* 
   This class was based on an example from javamex.com.  
   It was written by Neil Coffey.
*/
class genKeys {

    public static void main (String[] args) {
	try {
	    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
	    kpg.initialize(1024);

	    for (int i=0; i<2; i++) {
		KeyPair kp = kpg.genKeyPair();
		Key publicKey = kp.getPublic();
		Key privateKey = kp.getPrivate();

		KeyFactory fact = KeyFactory.getInstance("RSA");
		RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
						   RSAPublicKeySpec.class);
		RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
							 RSAPrivateKeySpec.class);

		if (i == 1) {
		    saveToFile(args[0] + "/sender-public.key", pub.getModulus(),
			       pub.getPublicExponent());
		    saveToFile(args[0] + "/sender-private.key", priv.getModulus(),
			       priv.getPrivateExponent());
		} else {
		    saveToFile(args[0] + "/dest-public.key", pub.getModulus(),
			       pub.getPublicExponent());
		    saveToFile(args[0] + "/dest-private.key", priv.getModulus(),
			       priv.getPrivateExponent());
		}
	    }

	} catch (Exception e) {
	    System.out.println(e);
	    System.exit(1);
	}
    }	

    public static void saveToFile(String fileName,
				  BigInteger mod, BigInteger exp) throws IOException {
	BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
	ObjectOutputStream oout = new ObjectOutputStream(bos);

	try {
	    oout.writeObject(mod);
	    oout.writeObject(exp);
	} catch (Exception e) {
	    throw new IOException("Unexpected error", e);
	} finally {
	    oout.close();
	}
    }
}
